﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyLib.Web.UI {
	/// <summary>
	/// 自定义签条
	/// </summary>
	[DefaultProperty("Text")]
	[ToolboxData("<{0}:MyLabel runat=\"server\"></{0}:MyLabel>")]
	public class MyLabel : Label {
		/// <summary>
		/// 
		/// </summary>
		private const string REQUIRED_CLASS = "required";

		/// <summary>
		/// 
		/// </summary>
		private const string RequiredMark = "(*)";

		private Style m_markerStyle;

		/// <summary>
		/// 
		/// </summary>
		[Bindable(true)]
		[Category("Action")]
		[DefaultValue(false)]
		public bool Required {
			get {
				var obj = ViewState["Required"];
				if (obj == null) {
					return false;
				} else {
					return (bool)obj;
				}
			}
			set {
				ViewState["Required"] = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Category("Styles")]
		[NotifyParentProperty(true)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
		[Description("MyLabel_MarkerStyle")]
		[PersistenceMode(PersistenceMode.InnerProperty)]
		public Style MarkerStyle {
			get {
				if (this.m_markerStyle == null) {
					this.m_markerStyle = new Style();
					if (base.IsTrackingViewState) {
						((IStateManager)this.m_markerStyle).TrackViewState();
					}
				}
				return this.m_markerStyle;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		protected override void RenderContents(HtmlTextWriter writer) {
			HttpUtility.HtmlEncode(Text, writer);

			// Append required marker.
			if (Required) {
				MarkerStyle.AddAttributesToRender(writer);
				writer.AddAttribute(HtmlTextWriterAttribute.Title, MyLib.Web.Properties.Main.FieldIsRequired);
				writer.RenderBeginTag(HtmlTextWriterTag.Span);
				writer.WriteEncodedText(RequiredMark);
				writer.RenderEndTag();
			}

			writer.WriteEncodedText(":");
		}
	} // end of MyLabel.
}
